import os
import path
import sys
import importlib

__api__ = None


class Api(object):
    def __init__(self, path, package='gateway'):
        self.path = path
        self.package = package
        self.gateways = {}
        self._init(path, package)


    def _init(self, path, package):
        for f in os.walk('{}{}{}'.format(path, os.path.sep, package)):
            dir = f[1]
            for name in dir:
                if not name.startswith('__') and not name.startswith('.'):
                    mod = importlib.import_module('{}.{}'.format(package, name))
                    self.gateways[name] = mod

    def get_gateway(self, gateway_id):
        return self.gateways.get(gateway_id, None)


def default():
    global __api__
    if __api__ is None:
        sdk_path = os.getenv('GATEWAY_SDK_PATH', os.path.abspath('.') )
        __api__ = Api(sdk_path)
    return __api__


def set_config(sdk_path, root_package=None):
    """Create new default api object with given configuration
    """
    global __api__
    __api__ = Api(sdk_path, root_package)
    return __api__


configure = set_config
